package com.yloveg.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.util.StringUtil;
import com.yloveg.base.BaseController;
import com.yloveg.base.EntityUtils;
import com.yloveg.base.ImageToBase64ToImage;
import com.yloveg.base.PictureChangeSize;
import com.yloveg.common.PageUtil;
import com.yloveg.common.UrlUtil;
import com.yloveg.dao.VPollLogsMapper;
import com.yloveg.entity.SPermission;
import com.yloveg.entity.SPermissionExtend;
import com.yloveg.entity.SRole;
import com.yloveg.entity.SRolePermission;
import com.yloveg.entity.SUserRole;
import com.yloveg.entity.Suser;
import com.yloveg.entity.UserInfo;
import com.yloveg.entity.VActivity;
import com.yloveg.entity.VGift;
import com.yloveg.entity.VPlayer;
import com.yloveg.entity.VPollLogs;
import com.yloveg.service.SPermissionService;
import com.yloveg.service.SRolePermissionService;
import com.yloveg.service.SRoleService;
import com.yloveg.service.SUserRoleService;
import com.yloveg.service.UserInfoService;
import com.yloveg.service.UserService;
import com.yloveg.service.VActivityService;
import com.yloveg.service.VGiftService;
import com.yloveg.service.VPlayerService;
import com.yloveg.service.VPollLogsService;

import net.sf.json.JSONObject;


@Controller
@RequestMapping({"activity"})  
public class ActivityController extends BaseController { 
	
	@Value("#{system.linux_url}")
	private String linux_url;
	@Value("#{system.img_path}")
	private String img_path;
	@Value("#{system.area_url}")
	private String area_url;
	
	@Autowired
    private VActivityService vActivityService;
	
	@Autowired
    private VGiftService vGiftService;
	
	@Autowired
    private VPlayerService vPlayerService;
	
	@Autowired
    private VPollLogsService vPollLogsService;
	
	
    
    @RequestMapping("/activityList")
    public String activityList(ModelMap map){
    	 return "landing/activity/activityList";
    }
    
    @RequestMapping("/queryActivityPage")
    @ResponseBody
    public Map<String, Object> queryActivityPage(int page, int limit, String status){
        Map<String, Object> map = PageUtil.dateToLayTable(vActivityService.queryActivityPage(page, limit,status));
        return map;
    }
    
    //活动新增（全量修改）
    @RequestMapping("/addActivity")
    public String addActivity(ModelMap map,int id){
    	VActivity vactivity=vActivityService.selectByPrimaryKeyN(id);
    	List<VGift> giftlistall=vGiftService.queryGift();
    	map.put("giftlistall", giftlistall);
    	if(vactivity==null) {
    		map.put("activity", new VActivity());
    		map.put("giftlistcheck", "");
    	}else {
    		map.put("activity", vactivity);
    		String gift=vactivity.getGift();
    		if(StringUtil.isEmpty(gift)) {
    			map.put("giftlistcheck", "");
    		}else {
        		map.put("giftlistcheck", gift);
    		}
    	}
    	return "landing/activity/addActivity";
    }    
    
    //基本信息修改
    @RequestMapping("/editActivity")
    public String editActivity(ModelMap map,int id){
    	VActivity vactivity=vActivityService.selectByPrimaryKeyN(id);
    	List<VGift> giftlistall=vGiftService.queryGift();
    	map.put("giftlistall", giftlistall);
    	if(vactivity==null) {
    		map.put("activity", new VActivity());
    		map.put("giftlistcheck", "");
    	}else {
    		map.put("activity", vactivity);
    		String gift=vactivity.getGift();
    		if(StringUtil.isEmpty(gift)) {
    			map.put("giftlistcheck", "");
    		}else {
        		map.put("giftlistcheck", gift);
    		}
    	}
    	return "landing/activity/editActivity";
    }    

    //编辑或新增
	@RequestMapping("/saveActivity")
	@ResponseBody
	public Map<String, Object> saveActivity(VActivity vactivity) throws IOException{
    	Date date=new Date();
    	DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    	String time=format.format(date);//time就是当前时间
    	System.out.println("活动开始时间："+time);
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		String url = "0";
    	if(vactivity.getId()==0) {
    		vactivity.setOwner(this.getSessionUser().getId());
    		vactivity.setDaynum(0);
    		vactivity.setTotalnum(0);
    		vactivity.setThumbnum(0);
    		vactivity.setPalyernum(0);
    		vactivity.setMoneyDay(new BigDecimal("0"));
    		vactivity.setMoneySum(new BigDecimal("0"));
    		vactivity.setHeadpic(ImageToBase64ToImage.Base64ToImage(vactivity.getHeadpic(),img_path, linux_url));
    		/*vactivity.setHeadpicsmall(ImageToBase64ToImage.Base64ToImage(vactivity.getHeadpicsmall(),img_path, linux_url));*/
    		vactivity.setActivitpic(ImageToBase64ToImage.Base64ToImage(vactivity.getActivitpic(),img_path, linux_url));
    		/*vactivity.setActivitpicsmall(ImageToBase64ToImage.Base64ToImage(vactivity.getActivitpicsmall(),img_path, linux_url));*/
    		result = vActivityService.insertActivity(vactivity);
    	}else {
    		if(vactivity.getHeadpic().indexOf("base64")!=-1) {
        		vactivity.setHeadpic(ImageToBase64ToImage.Base64ToImage(vactivity.getHeadpic(),img_path, linux_url));
        		/*vactivity.setHeadpicsmall(ImageToBase64ToImage.Base64ToImage(vactivity.getHeadpicsmall(),img_path, linux_url));*/
    		}
    		if(vactivity.getActivitpic().indexOf("base64")!=-1) {
        		vactivity.setActivitpic(ImageToBase64ToImage.Base64ToImage(vactivity.getActivitpic(),img_path, linux_url));
        		/*vactivity.setActivitpicsmall(ImageToBase64ToImage.Base64ToImage(vactivity.getActivitpicsmall(),img_path, linux_url));*/
    		}


    		result = vActivityService.updateByPrimaryKeySelective(vactivity);
    	}
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
    	Date date1=new Date();
    	String time1=format.format(date1);//time就是当前时间
        System.out.println("活动结束时间："+time1);
		return map;		
	}
	
	//编辑或新增
	@RequestMapping("/saveActivity2")
	@ResponseBody
	public Map<String, Object> saveActivity2(VActivity vactivity) throws IOException{
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		result = vActivityService.updateByPrimaryKeySelective(vactivity);
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;		
	}	

	//删除投票活动
	@RequestMapping("/deleteActivity")
	@ResponseBody
	public Map<String, Object> deleteActivity (VActivity vactivity) {
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		if(vactivity.getId()!=null) {
			vactivity.setSts("N");
			result = vActivityService.updateByPrimaryKeySelective(vactivity);
		}
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;
	}
	
	//关闭投票活动
	@RequestMapping("/closeActivity")
	@ResponseBody
	public Map<String, Object> closeActivity (VActivity vactivity) {
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		if(vactivity.getId()!=null) {
			VActivity vactivitynew=vActivityService.selectByPrimaryKeyN(vactivity.getId());
			VActivity vactivity1 = new VActivity();
			String flag=vactivitynew.getFlag();
			if(flag.equals("Y")) {
				vactivity1.setId(vactivity.getId());
				vactivity1.setFlag("N");
			}else {
				vactivity1.setId(vactivity.getId());
				vactivity1.setFlag("Y");
			}
			result = vActivityService.updateByPrimaryKeySelective(vactivity1);
		}
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;
	}
	//添加选手
    @RequestMapping("/addPlayer")
    public String addPlayer(ModelMap map,VPlayer vPlayer,Integer id){
    	if(id!=null) {
    		vPlayer = vPlayerService.selectByPrimaryKey(id);
    	}
    	map.put("vPlayer", vPlayer);
    	return "landing/activity/addPlayer";
    }  	
	//查看选手列表
	@RequestMapping("/playerList")
	public String PlayerList (ModelMap map,int id) {
		map.put("activityid", id);
		return "landing/activity/playerList";
	}
	//加票
	@RequestMapping("/addTicket")
	public String addTicket (ModelMap map,int id) {
		map.put("id", id);
		map.put("gifts", vGiftService.queryGift());
		return "landing/activity/addTicket";
	}
	
	@RequestMapping("/queryPlayerPage")
	@ResponseBody
	public Map<String, Object> queryPlayerPage(int page, int limit, int activityid){
	    Map<String, Object> map = PageUtil.dateToLayTable(vPlayerService.queryActivityPageByactivity(page, limit, activityid));
	    return map;
	}
	
    //编辑或新增
	@RequestMapping("/saveOrUpdatePlayer")
	@ResponseBody
	public Map<String, Object> saveOrUpdatePlayer(VPlayer vPlayer) throws IOException{
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		String url = "0";
		if(vPlayer.getId()==0) {
			vPlayer.setPlayerpic(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpic(),img_path, linux_url));
			vPlayer.setPlayerpicbig(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpicbig(),img_path, linux_url));
    		vPlayer.setPlayerno(vPlayerService.queryVPlayerNO(vPlayer)+1);
			vPlayer.setAmount(0.00);
			vPlayer.setPoll(0);
			result = vPlayerService.insertPlayer(vPlayer);
			if(result>0) {
				VActivity activity=vActivityService.selectByPrimaryKeyN(vPlayer.getActivityid());
				VActivity activityNew = new VActivity();
				activityNew.setPalyernum(activity.getPalyernum()+1);
				activityNew.setId(activity.getId());
				vActivityService.updateByPrimaryKeySelective(activityNew);
			}
		}else {
			    Map<String, Object> temp = EntityUtils.entityToMap(vPlayer);
			    if(temp.containsKey("playerpicbig")&&temp.get("playerpicbig")!=null) {
			    	if(vPlayer.getPlayerpic().indexOf("base64")!=-1) {
						vPlayer.setPlayerpic(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpic(),img_path, linux_url));
						vPlayer.setPlayerpicbig(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpicbig(),img_path, linux_url));			    		
			    	}

			    }
			    VPlayer vPlayert = vPlayerService.selectByPrimaryKey(vPlayer.getId());
				VPollLogs vp = new VPollLogs();
				vp.setPlayerid(vPlayer.getId());
				vp.setUser(getSessionUser().getId().toString());
				vp.setContent("票数由"+vPlayert.getPoll()+"变成"+vPlayer.getPoll());
				vPollLogsService.insert(vp);
				result = vPlayerService.updateByPrimaryKeySelective(vPlayer);				

		}
   
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;		
	}
	
    //加票
	@RequestMapping("/saveAddTicket")
	@ResponseBody
	public Map<String, Object> saveAddTicket(int id,int poll){
		int result = 0;
		Map<String, Object> map = new HashedMap<String, Object>();
		VPlayer	vPlayer = vPlayerService.selectByPrimaryKey(id);
		if(vPlayer.getPoll()>0) {
			vPlayer.setPoll(vPlayer.getPoll()+poll);
		}else {
			vPlayer.setPoll(poll);
		}
		VPollLogs vp = new VPollLogs();
		vp.setPlayerid(id);
		vp.setUser(getSessionUser().getId().toString());
		vp.setContent(String.valueOf(poll));
		vPollLogsService.insert(vp);
		VActivity activity=vActivityService.selectByPrimaryKeyN(vPlayer.getActivityid());
		activity.setThumbnum(activity.getThumbnum()+poll);
		vActivityService.updateByPrimaryKeySelective(activity);
		result = vPlayerService.updateByPrimaryKeySelective(vPlayer);
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;		
	}	
	
	@RequestMapping("/createUrl")
	public String createUrl(ModelMap map,int id) {
		String activityUrl =area_url+"/vote-admin/free/playerList?activityid="+String.valueOf(id);
		map.put("url", activityUrl);
		return "landing/activity/readUrl";
	}

}
